package com.toolkit.job;

import com.alibaba.fastjson2.JSON;
import com.toolkit.util.HttpAPIUtil;
import com.toolkit.util.RedisUtil;
import com.toolkit.util.SameCityUrlUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author qdl
 * @descripton TODO
 * @Date 2024/1/15 16:16
 */
@Slf4j
@Component
public class SameCityXxlJobHeader {

    @Autowired
    private SameCityUrlUtil sameCityUrlUtil;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private HttpAPIUtil httpAPIUtil;
    /**
     * 获取accessToken
     *
     * @param param
     * @return
     * @throws Exception
     */
    @XxlJob("sameCityAccessTokenXxlJobHeader")
    public ReturnT<String> didiAccessTokenXxlJobHeader(String param) {
        log.info("SameCityAccessTokenXxlJobHeader 开始执行");
        String data;
        try {
            HashMap map=new HashMap();
            map.put("random", String.valueOf(UUID.randomUUID()));
            map.put("timestamp",System.currentTimeMillis());
            HashMap paramMap=new HashMap<>();
            paramMap.put("account",sameCityUrlUtil.getAccount());
            paramMap.put("password",sameCityUrlUtil.getPassword());
            map.put("param",paramMap);
            String url = sameCityUrlUtil.getAccountTokenUrl();
            log.info("请求同城的url为:{},参数为:{}", url, map);
            data = httpAPIUtil.doPostJson(url, map);
            log.info("请求同城的url为:{},参数为:{},接口返回数据为:{}", url, map,data);
            Map stringMap = (Map) JSON.parse(data);
            if (stringMap.get("errorCode").equals("0")) {
                Map<String, Object> resultMap = (Map)  stringMap.get("data");
                String accessToken = (String) resultMap.get("accessToken");
                if (accessToken != null) {
                    log.info("同城的accessToken:{}", accessToken);
                    redisUtil.setCacheObject("sameCityAccessToken", accessToken, 3600, TimeUnit.SECONDS);//存入redis
                    log.info("存入redis的sameCityAccessToken:{}", accessToken);
                }
            }

        } catch (Exception e) {
            log.error("获取accessToken失败:{}", e.getMessage());
        }
        log.info("SameCityAccessTokenXxlJobHeader 执行结束");
        return ReturnT.SUCCESS;
    }
}
